import Vue from 'vue'
import axios from 'axios'
import ToastUtil from '@/utils/ToastUtil'
import StringUtil from '@/utils/StringUtil'
import router from '@/router'
import { clearLoginInfo } from '@/utils'

// create an axios instance
const request = axios.create({
  // baseURL: process.env.BASE_API, // api的base_url
  baseURL: (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl),
  withCredentials: true,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})
// request interceptor
request.interceptors.request.use(config => {
  // Do something before request is sent
  if (StringUtil.isNotEmpty(Vue.cookie.get('token'))) {
    config.headers['token'] = Vue.cookie.get('token') // 请求头带上token
  }
  return config
}, error => {
  // Do something with request err
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
request.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
   * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
   */
  response => {
    const res = response.data
    // console.log('全局正常返回=' + JSON.stringify(res))
    if (res.code === 200) {
      return res.data
    } else {
      if (res && res.code === 401) { // 401, token失效
        clearLoginInfo()
        router.push({ name: 'login' })
      }
      return Promise.reject(res)
    }
  },
  error => {
    let res = error.response.data
    console.log('全局异常返回=' + JSON.stringify(res))
    let data = {
      'code': res.code,
      'msg': res.message
    }
    ToastUtil.showErrorToast('全局提示:' + res.message)
    return Promise.reject(data)
  })

export default request
